package com.yidont.douyinhelper.util

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.text.TextUtils
import android.widget.Toast
import com.yidont.douyinhelper.DouYinHelperService
import com.yidont.douyinhelper.appContext

/**
 * 启动无障碍设置界面
 */
fun startAccessibilitySettings() {
    val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS).apply {
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    appContext.startActivity(intent)
}

/**
 * 无障碍是否开启
 */
fun isAccessibilitySettingsOn(): Boolean {
    val serviceName = "${appContext.packageName}/com.yidont.douyinhelper.DouYinHelperService"
    val string = Settings.Secure.getString(
        appContext.contentResolver,
        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
    )
    if (string != null) {
        TextUtils.SimpleStringSplitter(':').apply {
            setString(string)
        }.apply {
            while (hasNext()) {
                val next = next()
                loge("next: $next")
                if (next == serviceName) {
                    return true
                }
            }
        }
    }
    return false
}

fun copyText(text: String) {
    val cm = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    cm.setPrimaryClip(ClipData.newPlainText(appContext.packageName, text))
}

fun launchApp(packageName: String = "com.ss.android.ugc.aweme") {
    val intent = appContext.packageManager.getLaunchIntentForPackage(packageName)?.apply {
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    try {
        appContext.startActivity(intent)
    } catch (e: Exception) {
        Toast.makeText(appContext, "启动失败", Toast.LENGTH_SHORT).show()
    }
}